<template>
  <div class="user-info">
    
    <main class="content">
      <!-- 头像 -->
      <section class="info-item avatar-section" @click="handleAvatarClick">
        <div class="title">
         <uni-icons type="contact" size="20" color="gray"></uni-icons>
		  头像
        </div>
        <label for="avatar-upload" class="value">
          <img :src="avatarUrl" alt="Avatar" class="avatar" />
        </label>
        <!-- 文件选择器 -->
        <input id="avatar-upload" type="file" accept="image/*" @change="onAvatarChange" style="display: none;" />
        <div :class="[avatarState]" @click.stop="handleAvatarAction">{{ avatarButtonText }}</div>
      </section>

      <!-- 其他信息项 -->
      <section v-for="(item, index) in infoItems" :key="index" class="info-item" @click="handleClick(item)">
        <div class="title">
          <uni-icons :type="item.icon" size="20" color="gray"></uni-icons> <!-- 动态设置图标类型 -->
          {{ item.title }}
        </div>
        <input v-if="item.editing" v-model="item.value" :placeholder="item.placeholder" class="input-field" style="color: gray;" />
        <div v-else class="value">{{ item.value || item.placeholder }}</div>
        <div :class="[item.state]" @click.stop="handleAction(item)">{{ item.buttonText }}</div>
      </section>
    </main>
    <!-- 底部 -->
    <footer class="footer">
      <button class="save-btn" @click="saveInfo">
		  <uni-icons type="refreshempty" size="25" color="#fff"></uni-icons>
		  保存个人信息 
	</button>
    </footer>
	 <!-- 收货地址 -->
	
	   <!-- 地址选择模态框 -->
	   <view class="address-modal" v-if="showAddressModal">
	     <view class="modal-content">
	       <view class="modal-header">
	         <text>请选择地址</text>
	         <button @click="closeAddressModal" class="close">&times;</button>
	       </view>
	       <view class="modal-body">
	         <!-- 使用 picker 组件进行多列选择 -->
	         <picker mode="region" :value="selectedRegion" @change="handleRegionChange">
	           <view class="picker-placeholder">
                {{ selectedRegion[0] }} {{ selectedRegion[1] }} {{ selectedRegion[2] || '点击选择地区' }}
             </view>
	         </picker>
	       </view>
	       <view class="modal-footer">
	         <button @click="confirmAddress">下一步</button>
	       </view>
	     </view>
	   </view>
	   
	   <!-- 完善收货地址弹窗 -->
	   <view class="address-detail-modal" v-if="showAddressDetailModal">
	     <view class="modal-content">
	       <view class="modal-header">
	         <text>完善收货地址</text>
	         <button @click="closeAddressDetailModal" class="close">&times;</button>
	       </view>
	       <view class="modal-body">
	         <!-- 显示选择的地址 -->
	         <view class="selected-address">
               选择的地址: {{ selectedRegion[0] }} {{ selectedRegion[1] }} {{ selectedRegion[2] }}
             </view>
	         <textarea v-model="detailedAddress" placeholder="请输入详细地址"></textarea>
	       </view>
	       <view class="modal-footer">
	         <button @click="saveDetailedAddress">保存</button>
	       </view>
	     </view>
	   </view>

    <!-- 签署协议模态框 -->
    <div class="contract-modal" v-if="showContractModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>签署服务协议</h3>
          <button @click="closeContractModal" class="close">&times;</button>
        </div>
        <div class="modal-body">
          <p style="color: red;">请先点击蓝色文字认真阅读每项协议，勾选后则代表您已知晓并同意对应协议和平台声明。</p>
          <checkbox-group @change="handleCheckboxChange">
            <div class="agreement-item">
              <label>
                <checkbox value="agreement1" :checked="agreements.agreement1" />
                <a href="#" @click.prevent="openAgreement('agreement1')" class="agreement-link">《代收代付服务协议》</a>
              </label>
            </div>
            <div class="agreement-item">
              <label>
                <checkbox value="agreement2" :checked="agreements.agreement2" />
                <a href="#" @click.prevent="openAgreement('agreement2')" class="agreement-link">《免责声明服务协议》</a>
              </label>
            </div>
          </checkbox-group>
        </div>
        <div class="modal-footer">
          <button @click="signContract">我同意并签署</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      avatarUrl: 'https://example.com/default-avatar.png',
      avatarState: 'actionone', // 初始化为修改状态
      avatarButtonText: '修改', // 初始化为修改文本

      infoItems: [
        { title: '微信昵称', icon: 'person', value: '', placeholder: '超好用的电子评价卡', state: 'action', buttonText: '完善', editing: false },
        { title: '姓名', icon: 'list', value: '', placeholder: '请输入姓名', state: 'action', buttonText: '完善', editing: false },
        { title: '手机号', icon: 'phone', value: '', placeholder: '未填写', state: 'action', buttonText: '完善', editing: false },
        { title: '收货地址', icon: 'location', value: '', placeholder: '未填写', state: 'action', buttonText: '完善', editing: false },
        { title: '签署协议', icon: 'bars', value: '', placeholder: '未签署服务协议', state: 'action', buttonText: '完善', editing: false }
      ],
      showAddressModal: false,
      showAddressDetailModal: false,
      selectedRegion: ['', '', ''], // 初始化为空数组
      detailedAddress: '',
      showContractModal: false,
      agreements: {
        agreement1: false,
        agreement2: false
      },
    };
  },
  methods: {
	   saveDetailedAddress() {
	     if (!this.detailedAddress) {
         wx.showToast({
           title: '请输入详细地址',
           icon: 'none',
           duration: 2000
         });
         return;
        }
       
       // 组合完整地址
       const fullAddress = `${this.selectedRegion[0]} ${this.selectedRegion[1]} ${this.selectedRegion[2]} ${this.detailedAddress}`;
       
       // 更新收货地址信息项
       const addressItem = this.infoItems.find(item => item.title === '收货地址');
       if (addressItem) {
         addressItem.value = fullAddress;
         addressItem.state = 'actionone';
         addressItem.buttonText = '修改';
       }
       
       // 保存到本地存储
       wx.setStorageSync('detailedAddress', this.detailedAddress);
       wx.setStorageSync('selectedRegion', this.selectedRegion);
       
       wx.showToast({
         title: '保存成功',
         icon: 'success',
         duration: 2000
       });
       
       this.showAddressDetailModal = false;
	   },

	  handleRegionChange(e) {
	   this.selectedRegion = e.detail.value;
      this.hasSelectedAddress = true; // 用户选择了地址后更新标志位
      console.log('Selected Region:', this.selectedRegion);
	  },

	  handleCheckboxChange(e) {
	    const values = e.detail.value;
	    this.agreements.agreement1 = values.includes('agreement1');
	    this.agreements.agreement2 = values.includes('agreement2');
	  },
	
    goBack() {
      this.$router.back();
    },
    handleAvatarClick() {
      if (this.avatarState === 'actionone') {
        document.getElementById('avatar-upload').click(); // 触发文件选择器
      }
    },
    onAvatarChange(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = e => {
          this.avatarUrl = e.target.result;
          this.prepareSaveAvatar(); // 准备保存头像
        };
        reader.readAsDataURL(file);
      }
    },
    prepareSaveAvatar() {
      this.avatarState = 'actiontwo';
      this.avatarButtonText = '保存';
    },
    saveAvatar() {
      console.log('头像已保存');
      this.avatarState = 'actionone';
      this.avatarButtonText = '修改';
    },
    handleAvatarAction() {
      switch (this.avatarState) {
        case 'actionone':
          this.handleAvatarClick();
          break;
        case 'actiontwo':
          this.saveAvatar();
          break;
      }
    },
    handleClick(item) {
      if (item.title === '收货地址') {
        this.showAddressModal = true;
      } else if (item.title === '签署协议') {
        this.showContractModal = true; // 显示服务协议模态框
      } else if (item.state === 'action') {
        this.prepareEdit(item);
      }
    },
    closeContractModal() {
      this.showContractModal = false;
    },
   signContract() {
     if (!this.agreements.agreement1 || !this.agreements.agreement2) {
       wx.showToast({
         title: '请确保所有协议都已勾选！',
         icon: 'none',
         duration: 2000
       });
       return;
     }
     wx.showToast({
       title: '您已成功签署服务协议',
       icon: 'success',
       duration: 2000
     });
     this.closeContractModal();
     const item = this.infoItems.find(i => i.title === '签署协议');
     item.value = '您已签署';
     item.state = 'actiontwo';
     item.buttonText = '保存';
   },
    // openAgreement(agreementId) {
    //   alert(`查看 ${agreementId} 协议`);
    // },
	openAgreement(agreementId) {
	  wx.showModal({
	    title: '协议查看',
	    content: `您正在查看 ${agreementId} 协议`,
	    success(res) {
	      if (res.confirm) {
	        console.log('用户点击确定');
	      } else if (res.cancel) {
	        console.log('用户点击取消');
	      }
	    }
	  })
	},
    handleAction(item) {
      switch (item.state) {
        case 'action':
          this.prepareEdit(item);
          break;
        case 'actiontwo':
          this.saveInfoItem(item);
          break;
        case 'actionone':
          this.editInfo(item);
          break;
      }
    },
    prepareEdit(item) {
      item.editing = true;
      item.state = 'actiontwo';
      item.buttonText = '保存';
    },
    saveInfoItem(item) {
      item.editing = false;
      item.state = 'actionone';
      item.buttonText = '修改';
    },
    editInfo(item) {
      item.editing = true;
      item.state = 'actiontwo';
      item.buttonText = '保存';
    },
    saveInfo() {
		  wx.showModal({
		    title: '提示',
		    content: '保存信息成功，请先完善门店信息',
		    showCancel: false,
		    success(res) {
		      if (res.confirm) {
		        console.log('用户点击确定');
		      }
		    }
		  });
		  console.log(this.infoItems.value);
	  	},
		closeAddressModal() {
		  this.showAddressModal = false;
		},
		confirmAddress() {
		  if (!this.selectedRegion[0] || !this.selectedRegion[1] || !this.selectedRegion[2]) {
        wx.showToast({
          title: '请选择完整地址',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      this.showAddressModal = false;
      this.showAddressDetailModal = true;
		},
		closeAddressDetailModal() {
		  this.showAddressDetailModal = false;
		},
		updateAddressButtonState(item) {
		  if (item && item.value) {
		    item.state = 'actiontwo';
		    item.buttonText = '保存';
		  } else {
		    item.state = 'action';
		    item.buttonText = '完善';
		  }
		}
  }
}
</script>

<style scoped>
/* 整体部分 */
.user-info {
  font-family: Arial, sans-serif;
}

/* 头像部分 */
.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background-color: #fff;
  border: 1px solid #ddd;
  margin-bottom: 10px;
}

.avatar-section {
  position: relative;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.title {
  color: black;
  font-weight: 800;
  flex-grow: 1;
}

.input-field {
  flex-grow: 1;
  padding: 5px;
  margin-left: 10px;
  border-radius: 4px;
}

.action,
.actiontwo,
.actionone {
  color: #fff;
  cursor: pointer;
  padding: 10px;
  border-radius: 15px;
}

.action {
  background-color: #c44e49;
}

.actiontwo {
  background-color: #2b7bfd;
}

.actionone {
  background-color: #77c94b;
}

.footer {
  padding: 20px;
  background-color: #fff;
  width: 90%;
}

.save-btn {
  width: 90%;
  padding: 10px;
  background-color: rgb(119, 201, 75);
  color: #fff;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 地址选择相关样式 */
.picker-placeholder {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin: 10px 0;
}

.selected-address {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.modal-body textarea {
  width: 100%;
  height: 100px;
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* 签署合同部分 */
.contract-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  width: 80%;
  max-width: 600px;
}

.modal-body p {
  white-space: pre-line;
  color: red;
}

.agreement-item {
  margin-bottom: 0px;
}

.agreement-link {
  color: blue;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

.modal-footer button {
  margin-top: 15px;
  padding: 10px 20px;
  background-color: #77c94b;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>